﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

/*1.使控件不获取焦点：IsHitTestVisible*/
/*2.强制刷新Adorner：InvalidateVisual*/
namespace DrawLibrary.Adorners
{
    public class CrossAdorner : Adorner
    {
        private Point mousePosition;
        public CrossAdorner(UIElement adornedElement) : base(adornedElement)
        {
            this.IsHitTestVisible = false; 
            adornedElement.MouseMove += AdornedElement_MouseMove;
        }
        private void AdornedElement_MouseMove(object sender, MouseEventArgs e)
        {
            mousePosition = e.GetPosition(this);
            this.InvalidateVisual(); // 强制刷新Adorner
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            Rect adornedElementRect = new Rect(this.AdornedElement.RenderSize);

            Pen renderPen = new Pen(new SolidColorBrush(Colors.Red), 1.0);

            //绘制十字
            drawingContext.DrawLine(renderPen, new Point(adornedElementRect.Left, mousePosition.Y), new Point(adornedElementRect.Right, mousePosition.Y));
            drawingContext.DrawLine(renderPen, new Point(mousePosition.X, adornedElementRect.Top), new Point(mousePosition.X, adornedElementRect.Bottom));

            string coordinates = $"X: {mousePosition.X:F1}, Y: {mousePosition.Y:F1}";
            FormattedText formattedText = new FormattedText(
                coordinates,
                CultureInfo.CurrentCulture,
                FlowDirection.LeftToRight,
                new Typeface("Arial"),
                12,
                Brushes.Black,
                1.25
            );

            double x = mousePosition.X + 10;
            double y = mousePosition.Y + 10;
            double margin = 2;
            drawingContext.DrawRectangle(Brushes.White, new Pen(Brushes.Black, 1), new Rect(x, y, formattedText.Width + 2 * margin, formattedText.Height + 2 * margin));
            drawingContext.DrawText(formattedText, new Point(x + margin, y + margin));
        }
    }
}
